package com.cloud.common.support;

import com.alibaba.cloud.nacos.client.NacosPropertySource;
import com.alibaba.cloud.nacos.client.NacosPropertySourceLocator;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.boot.autoconfigure.condition.ConditionalOnBean;
import org.springframework.core.env.CompositePropertySource;
import org.springframework.core.env.Environment;
import org.springframework.core.env.PropertySource;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import java.util.Collection;

@Slf4j
@Component
@ConditionalOnBean(NacosPropertySourceLocator.class)
public class NacosConfigPrinter implements ApplicationRunner {
    @Autowired
    private NacosPropertySourceLocator locator;

    @Autowired
    private Environment env;

    @Override
    public void run(ApplicationArguments args) {
        String configPrint = env.getProperty("nocos.config.print");
        if (StringUtils.isEmpty(configPrint) || !configPrint.equals(Boolean.TRUE.toString())) {
            return;
        }
        print();
    }

    public void print() {
        log.info("========nacos config print begin========");
        PropertySource<?> propertySource = locator.locate(env);
        if (propertySource instanceof CompositePropertySource) {
            CompositePropertySource compositePropertySource = (CompositePropertySource) propertySource;
            Collection<PropertySource<?>> propertySources = compositePropertySource.getPropertySources();
            if (CollectionUtils.isEmpty(propertySources)) {
                return;
            }
            propertySources.stream()
                    .filter(source -> source instanceof NacosPropertySource)
                    .map(source -> (NacosPropertySource) source).forEach(
                        nacosPropertySource -> {
                            log.info("nacos config dataId=>[{}]", nacosPropertySource.getName());
                            if (!CollectionUtils.isEmpty(nacosPropertySource.getSource())) {
                                StringBuilder builder = new StringBuilder("nacos config dataValue:\n\n");
                                nacosPropertySource.getSource().entrySet().forEach(etry -> {
                                    builder.append(String.format("\"%s\":\"%s\"\n", etry.getKey(), etry.getValue()));
                                });
                                log.info(builder.toString());
                            }
                        }
            );
        }
        log.info("========nacos config print finish========");
    }
}
